<?php

namespace app\common\model;

use app\common\util\ErrorCode;
use app\common\util\Tools;
use think\Model;

/**
 * Class Auth
 * @package app\common\model
 * 后台账号sessionId表
 */
class trAdminSession extends Model
{
    protected $pk = 'id';
    protected $resultSetType = 'collection'; //申明结果集是数据集对象（collection），查询结果才能用toArray()方法转为数组
    protected $name = "admin_session"; //表名

    protected $type = [
        'expire_time'  =>  'timestamp:Y-m-d H:i',
        'create_time'  =>  'timestamp:Y-m-d H:i',
    ];

    //获取多字段数据
    public static function getList($field = '*', $filter = [], $page = 1, $limit = 10, $order = "create_time desc"){
        $db = self::where($filter)->field($field)->order($order);
        if($page && $limit)
            $db->limit($page-1, $limit);
        $data = $db->select();
        $data = Tools::transferFields($data->toArray());
        return $data;
    }

    //获取多字段数据
    public static function getFields($field, $filter = [], $one = true, $toArray = true){
        if($one){
            $data = self::where($filter)->field($field)->find();
            return $data ? ($toArray ? Tools::transferFields($data->toArray()) : Tools::transferFields($data->getData())) : [];
        }else{
            $data = self::where($filter)->field($field)->select();
            return $data ? ($toArray ? Tools::transferFields($data->toArray()) : $data) : [];
        }
    }

    //添加
    public static function add($data, $getId=false){
        if(!$data)
            return true;
        try {
            $model = self::create($data);
            if ($getId) {
                return $model->id;
            } else {
                return true;
            }
        }catch (\Exception $e){
            return ErrorCode::code("try_error", $e->getMessage());
        }
    }

    //更新
    public static function doUpdate($data, $filter = []){
        if(!$data)
            return true;
        return self::update($data, $filter);
    }
}